﻿#region Header
/*
 * name：TxtResourceProvider
 * author：Kain
 * date：12/15/2010 4:25:43 PM
 *********************************************
 * History:
 * $Header$
 * $History$
 */
#endregion

#region imported namespace
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.IO;
using System.Text.RegularExpressions;
using Janus.Cores.Configuration;
#endregion

namespace Janus.Cores.Globalization
{
    /// <summary>
    /// dllMultiLanguage 的IResourcesProvider实现
    /// </summary>
    public class TxtResourceProvider : IResourcesProvider
    {
        Dictionary<string, Entry> _items = new Dictionary<string, Entry>();
        static string __lngName ;
        static TxtResourceProvider()
        {
            __lngName = EBSConfiguration.Current.ApplicationSection.CurrentCulture;
            if (string.IsNullOrEmpty(__lngName))
                __lngName = System.Threading.Thread.CurrentThread.CurrentUICulture.Name;
        }
        string resourceName;
        #region private variable

        #endregion

        #region properies

        #endregion
        /// <summary>
        /// 
        /// </summary>
        public TxtResourceProvider()
            : this(string.Empty)
        {

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="resourceName"></param>
        public TxtResourceProvider(string resourceName)
        {
            this.resourceName = resourceName;
            LoadItems();
        }

        #region methods

        #region public

        #endregion

        #region protected

        #endregion

        #region private
        Regex reg = new Regex(@"^(?<key>[^;,^[].+)=(?<value>.+)$");
        Dictionary<string, Entry> GetEntryFromStream(Stream stream, string lngCode, Dictionary<string, Entry> entries)
        {
            if (stream == null)
                return null;
            using (var rd = new StreamReader(stream, System.Text.Encoding.Default))
            {
                while (rd.Peek() >= 0)
                {
                    var line = rd.ReadLine();
                    var m = reg.Match(line);
                    if (m.Success)
                    {
                        var key = m.Groups["key"].Value.Trim().ToLower();
                        var value = m.Groups["value"].Value;

                        Entry entry;
                        if (!entries.TryGetValue(key, out entry))
                        {
                            entry = new Entry();
                            entry.Key = key;
                            entries.Add(key, entry);
                        }
                        entry[lngCode] = value;
                    }
                }
            }
            return entries;
        }

        void LoadItems()
        {

            if (_items.Keys.Count > 0)
                return;
            lock (_items)
            {
                string localPath = GetPath();
                var dir = new DirectoryInfo(localPath);
                if (!dir.Exists)
                    throw new FileNotFoundException("为没有找到资源文件对应的路径:" + localPath);
                var lngCodes = GetLangageCode(localPath);

                foreach (var item in lngCodes)
                {
                    GetEntries(item, localPath, _items);
                }
            }
        }

        List<string> GetLangageCode(string path)
        {
            var dir = new DirectoryInfo(path);
            var files = dir.GetFiles("*.lng");
            return files.Select(c =>
                {
                    var temp = c.Name.Split('.');
                    if (temp.Length > 1)
                        return temp[temp.Length - 2];
                    else
                        return string.Empty;
                }
            ).Where(c => !string.IsNullOrWhiteSpace(c)).Distinct().ToList();
        }

        Dictionary<string, Entry> GetEntries(string lngCode, string path, Dictionary<string, Entry> entries)
        {
            string defaultFile = Path.Combine(path, lngCode + ".lng");
            if (!File.Exists(defaultFile))
                throw new FileNotFoundException("没有找到" + lngCode + "对应的默认语言文件:" + defaultFile);

            var files = Directory.GetFiles(path, "*." + lngCode + ".lng");
            foreach (var file in files)
            {
                entries = GetEntryFromStream(new FileStream(file, FileMode.Open, FileAccess.Read), lngCode, entries);
            }

            entries = GetEntryFromStream(new FileStream(defaultFile, FileMode.Open, FileAccess.Read), lngCode, entries);
            return entries;
        }

        private string GetPath()
        {
            return Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, @"App_Data\Language");
        }

        #endregion

        #endregion

        /// <summary>
        /// 
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public string GetString(string name)
        {
            return GetString(name, __lngName);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="name"></param>
        /// <param name="culture"></param>
        /// <returns></returns>
        public string GetString(string name, System.Globalization.CultureInfo culture)
        {
            return GetString(name, culture.Name);
        }

        private string GetString(string name, string lngName)
        {
            name = name.ToLower();
            Entry entry;
            if (_items.TryGetValue(name, out entry))
                return entry[lngName];
            return name;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public object GetObject(string name)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="name"></param>
        /// <param name="culture"></param>
        /// <returns></returns>
        public object GetObject(string name, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
        
        public IEnumerable<string> Keys {
            get {
                return _items.Keys;
            }
        }
    }

}
